package com.douziit.meilianoa.base.utils.http;


import javax.servlet.http.HttpServletRequest;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017/11/24
 */
public class WebUtil {

    /**
     * 获取网站url
     *
     * @param request
     * @return
     */
    public static String getWebUrl(HttpServletRequest request) {
        return String.valueOf(request.getRequestURL());
    }


    /**
     * 获取网站域名前缀
     *
     * @param request
     * @return
     */
    public static String getContextPathUrl(HttpServletRequest request) {
        Integer port = request.getServerPort();
        //当前链接使用的协议
        String url = request.getScheme()
                //服务器地址
                + "://" + request.getServerName()
                //端口号
                + (port == 80 ? "" : ":" + port)
                + request.getContextPath();
        return url;
    }

    /**
     * 获取网站域名
     *
     * @param request
     * @return
     */
    public static String getDomain(HttpServletRequest request) {
        Integer port = request.getServerPort();
        //当前链接使用的协议
        String url = request.getScheme()
                //服务器地址
                + "://" + request.getServerName()
                //端口号
                + (port == 80 ? "" : ":" + port);
        return url;
    }



    /**
     * 获取客户端ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }




    /***
     * 计算两点之间的距离
     * @param lng1 当前经度
     * @param lat1 当前纬度
     * @param lng2 目标经度
     * @param lat2 目标纬度
     * @return
     */
    public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
        double dis = Math.round(
                6378.138 * 2 * Math.asin(
                        Math.sqrt(Math.pow(Math.sin((lat1 * Math.PI / 180 - lat2 * Math.PI / 180) / 2), 2)
                                + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.pow(
                                Math.sin((lng1 * Math.PI / 180 - lng2 * Math.PI / 180) / 2), 2)
                        )
                ) * 1000
        );
        return dis;
    }

}
